﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ivony.Data;

namespace XCommunity.Data
{
  public static class AccountDataProvider
  {

    public readonly static SqlDbUtility DbUtility = new SqlDbUtility( @"Data Source=(local);Initial Catalog=XCommunity;Integrated Security=True" );


    /// <summary>
    /// 验证用户帐户的登录凭据
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    public static bool ValidateAccount( ref string username, byte[] password )
    {
      object result = DbUtility.ExecuteScalar( "SELECT Username FROM Accounts WHERE LOWER( Username ) = LOWER ( {0} ) AND Password = {1}", username, password );
      if ( result == null )
        return false;

      username = (string) result;
      return true;
    }


    /// <summary>
    /// 获取用户名的正确大小写形式
    /// </summary>
    /// <param name="username"></param>
    /// <returns></returns>
    public static string GetUsername( string username )
    {
      return (string) DbUtility.ExecuteScalar( "SELECT Username FROM Accounts WHERE LOWER( Username ) = LOWER ( {0} )", username );
    }

    /// <summary>
    /// 创建一个用户帐户
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    public static bool CreateAccount( string username, byte[] password )
    {
      return DbUtility.ExecuteNonQuery( "IF NOT EXISTS ( SELECT Username FROM Accounts WHERE LOWER( Username ) = LOWER ( {0} ) ) INSERT INTO Accounts ( Username, Password ) VALUES ( {0}, {1} );", username, password ) > 0;
    }
  }
}
